# -*- encoding: utf-8 -*-
__author__ = 'jia200x'

from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authorization import Authorization
from tastypie.validation import Validation
from api.models import Tema, Voto
from tastypie.serializers import Serializer
import simplejson
import csv
import StringIO

class CustomSerializer(Serializer):
    def to_json(self, data, options=None):
        options = options or {}
        data = self.to_simple(data,options)
        return simplejson.dumps(data,sort_keys=True)


class VotoValidation(Validation):
    def is_valid(self, bundle, request=None):
        errors = {}
        req_fields = ['na','tema']
        for k in req_fields:
            if not k in bundle.data.keys():
                errors[k] = 'Falta el registro'
        if len(errors) > 0:
            return errors
        try:
            int(bundle.data['na'])
        except:
            return {'na': "Número de alumno inválido"}

        na_fail = True
        try:
            cmp_obj = Voto.objects.get(na=bundle.data['na'])
        except:
            na_fail = False
        if na_fail == True:
            return {'na': "Ya existen registros del número de alumno"}

class TemaValidation(Validation):
    def is_valid(self, bundle, request=None):
        errors = {}
        req_fields = ['titulo','area','descripcion','autor','uai']
        for k in req_fields:
            if not k in bundle.data.keys():
                errors[k] = 'Falta el registro'
        if len(errors) > 0:
            return errors
    #Agregar lo del numero de votos
class TemaResource(ModelResource):
    titulo = fields.CharField(attribute='titulo')
    area = fields.CharField(attribute='area')
    descripcion = fields.CharField(attribute='descripcion')
    autor = fields.CharField(attribute='autor')
    uai = fields.CharField(attribute='uai')
    academico = fields.CharField(attribute='academico')
    fecha = fields.DateTimeField(attribute='fecha',readonly=True)

    def dehydrate(self, bundle):
        n=Voto.objects.filter(tema=bundle.data['id']).count()
        bundle.data['votos'] = n
        return bundle

    class Meta:
        queryset = Tema.objects.all()
        resource_name = 'tema'
        allowed_methods = ['get','post']
        authorization = Authorization()
        validation = TemaValidation()
        serializer = CustomSerializer()
        always_return_data = True

class VotoResource(ModelResource):
    na = fields.CharField(attribute='na')
    tema = fields.ForeignKey('api.resources.TemaResource','tema', blank=True)
    fecha = fields.DateTimeField(attribute='fecha')

    class Meta:
        queryset = Voto.objects.all()
        resource_name = 'voto'
        allowed_methods = ['get','post']
        authorization = Authorization()
        validation = VotoValidation()
        serializer = CustomSerializer()
